<?php

require_once('kan.inc');
include_once('utils/Database.php');

$db = new Database();

// get the identifiers for all sites in this installation
$query = "SELECT SiteIdentifier FROM sites";
$sites = $db->query($query)->getResult();

// get the url that redirected us to the handler in order to determine which content
// the user wanted to load
$request = isset($_SERVER['REDIRECT_URL']) ? $_SERVER['REDIRECT_URL'] : "/";

// explode on / to find all the different request parts
$parts = explode('/', $request);

// flag to determine whether or not we've found content
$found = false;

// the first element will be empty to we get rid of it
array_shift($parts);

// if we are running a typical localhost installation, then the second parameter
// will be the folder in which we are running the kan install from, so we rid that as well
//if( $_SERVER['HTTP_HOST'] == "localhost" ) {
//	array_shift($parts);
//}
// next try to determine the site id from the list of passed parameters
// once a valid site id is found, remove all other parameters
$siteid = -1;
foreach ($parts as $part) {

    if (count($sites) > 1) {
        // loop through the various site ids to determine if the current part is actually a site id
        foreach ($sites as $site) {
            if ($site['SiteIdentifier'] == $part) {
                // we'll store this data as our $_GET['siteid'] parameter for later processing
                // by the SiteLoader library
                $siteid = $part;
                $_GET['siteid'] = $siteid;

                // once found, remove the site id from the parameters list
                array_shift($parts);
                break;
            }
        }
    } else {
        if ($sites['SiteIdentifier'] == $part) {
            // we'll store this data as our $_GET['siteid'] parameter for later processing
            // by the SiteLoader library
            $siteid = $part;
            $_GET['siteid'] = $siteid;

            // once found, remove the site id from the parameters list
            array_shift($parts);
            break;
        }
    }

    // if the current part was not a siteid, then remove it
    if ($siteid == -1) {
        array_shift($parts);
    }
    // else stop the iteration and continue site load
    else {
        break;
    }
}

// if we did not find a valid site, try to load the default site
if ($siteid == -1) {
    $query = "SELECT * FROM sites WHERE SiteType = 'main'";
    $row = $db->query($query)->getRow();

    // we'll store this data as our $_GET['siteid'] parameter for later processing
    // by the SiteLoader library
    $siteid = isset($row['SiteIdentifier']) ? $row['SiteIdentifier'] : -1;
    $_GET['siteid'] = $siteid;

    // after all this, the siteid is empty or invalid, 
    // then trigger an error and kill the load process
    if (empty($siteid) || $siteid == -1) {
        die("Could Not Find A Valid Site In This Installation. Site Load Process Cancelled.");
    }
}

// include the core processing file
include_once('SiteLoader.php');

$cache = new Cache();
$cache->beginCaching();

// next we need to know which content we are trying to load
$contentType = isset($parts[0]) ? $parts[0] : "";
array_shift($parts);

// based on the content type, we'll load the required processor, with the rest
// of the array as the parameters
$parameters = implode("/", $parts);

switch ($contentType) {

    // special case for feeds. This will be resolved with a controller later
    case 'feed':
        $found = true;
        $params = explode("/", $parameters);
        $_GET['content'] = isset($params[0]) ? $params[0] : "";
        $_GET['category'] = isset($params[1]) ? $params[1] : "";

        $fv = new FeedView();
        $fv->render();

        break;
 

    default:
        
        // store parameters for use by controller render function
        $_GET['url'] = $parameters;
        
        // determine if a controller or manager instance exists
        $controller_name = String::toCamel($contentType . '_controller');
        $manager_name = String::toCamel($contentType . '_manager');
        
        // check for managers first, since they are more likely to exist than controllers
        // to improve performance
        if( class_exists($manager_name) && is_subclass_of($manager_name,"Manager") ) {
            $manager = new $manager_name();
            $manager->render();
            
            $found = true;
        }
        
        else if( class_exists($controller_name) && is_subclass_of ($controller_name, "Controller") ) {
            $controller = new $controller_name();
            $controller->render();
            $found = true;
        }
        
        else {
            $_GET['page'] = $parameters;

            $pm = new PageManager();
            $pm->render();

            $found = true;
        }
        
        break;
}

if ($found) {
    // output a header to say the content exists, other a 404 will be sent
    @header('HTTP/1.1: 200 OK');
} else {
    // no content was found. this should be automatically sent by the
    // server anyway, but we'll specify anyway just in case
    @header('HTTP/1.0 404 Not Found');
    echo 'The content you are looking for could not be found. Please check the URL you are trying to visit and try again';
}

// end the caching process
$cache->endCaching();
?>